package com.bwie.service;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.User;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @Author GaoYiJie
 * @Description
 * @Create 2025/3/12 9:10
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    HttpServletRequest request;

    @Override
    public R register(User user) {
        //格式验证
        String regex = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
        boolean matches = Pattern.matches(regex, user.getPhone());
        if (!matches){
            return R.ERROR(500,"手机号格式不正确");
        }
        //唯一验证
        User userDB = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getPhone, user.getPhone()).last("limit 1"));
        if (userDB != null){
            return R.ERROR(500,"用户已存在");
        }
        //注册
        user.setBalance(30.0);
        userMapper.insert(user);
        return R.OK();
    }

    @Override
    public R sendPhoneCode(String phone) {
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码:"+code);

        MobileMessageUtil.sendMobileMessage(phone,code);
        String phoneKey = "phone_code:"+phone;
        stringRedisTemplate.opsForValue().set(phoneKey,code,5, TimeUnit.MINUTES);

        return R.OK();
    }

    @Override
    public R login(LoginInfoVo loginInfoVo) {
        //判断用户是否存在
        User userDB = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getPhone, loginInfoVo.getPhone()).last("limit 1"));
        if (userDB == null){
            return R.ERROR(500,"用户不存在");
        }

        //判断验证码
        String phoneKey = "phone_code:"+loginInfoVo.getPhone();
        String codeRedis = stringRedisTemplate.opsForValue().get(phoneKey);
        if (codeRedis == null){
            return R.ERROR(500,"验证码失效");
        }
        if (!loginInfoVo.getCode().equals(codeRedis)){
            return R.ERROR(500,"验证码错误");
        }

        //JWT
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", userDB.getId()).claim("userName", userDB.getUsername()).compact();
        String tokenKey = "login_token:"+userDB.getId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,15,TimeUnit.MINUTES);

        userDB.setToken(token);
        return R.OK(userDB);
    }

    @Override
    public R getCount() {
        //获取登录用户ID
        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);


        Integer count = userMapper.selectCount(new QueryWrapper<User>().lambda().eq(User::getParentId, userId));

        return R.OK(count);
    }

    @Override
    public R updateFee(User user) {
        userMapper.updateById(user);
        return R.OK();
    }
}
